package team.xiaobaiya.gptchatrobot.rights;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.xiaobaiya.gptchatrobot.entity.database.UserKey;
import team.xiaobaiya.gptchatrobot.service.UserKeyService;

/**
 * @ClassName RightsManager
 * @Author Feng Yingnan
 * @Email fengyn1211@163.com
 * @Date 2023/4/17 13:40
 */
@Slf4j
@Component
public class RightsManager {

    @Autowired
    UserKeyService userKeyService;

    /**
     * 检查user key
     * @param userKey user key
     * @return 检查结果
     */
    public UserKeyCheckResult userKeyCheck(String userKey) {
        if (userKey == null || (userKey = userKey.trim()).equals("")) {
            return UserKeyCheckResult.USER_KEY_EMPTY;
        }
        UserKey keyInfo = userKeyService.selectByUserKey(userKey);
        if (keyInfo == null) {
            return UserKeyCheckResult.USER_KEY_INVALID;
        }
        if (keyInfo.getLoading()) {
            return UserKeyCheckResult.USER_KEY_ON_LOADING;
        }
        if (keyInfo.getUsage() < 0) {
            return UserKeyCheckResult.USER_KEY_USAGE_INSUFFICIENT;
        }
        return UserKeyCheckResult.USER_KEY_OK;
    }


    /**
     * 用户积分减少1
     * @param userKey user key
     */
    public void decrementUsage(String userKey) {
        if (!userKeyService.decrementUserUsage(userKey)) {
            log.info("{}积分减少失败", userKey);
        }
    }

    /**
     * 锁定 userKey
     * @param userKey user key
     */
    public void lockUserKey(String userKey) {
        userKeyService.setUserKeyLoading(userKey);
    }

    /**
     * 取消锁定 userKey
     * @param userKey user key
     */
    public void unlockUserKey(String userKey) {
        if (!userKeyService.setUserKeyUnloading(userKey)) {
            log.warn("{}loading状态更新失败，将影响用户使用", userKey);
        }
    }


}
